#!/bin/sh

PATH=/bin:/sbin:/usr/bin:/usr/sbin
export PATH

# ------------------------------------------------------------
# Set suid

chmod 4755 '/Library/Application Support/org.pqrs/Karabiner-Elements/bin/karabiner_session_monitor'

# ------------------------------------------------------------
# Set immutable flag

chflags uchg,schg /Applications/Karabiner-Elements.app
chflags uchg,schg /Applications/Karabiner-EventViewer.app

# ------------------------------------------------------------
# Relaunch karabiner processes

killall karabiner_kextd
killall karabiner_grabber
killall karabiner_observer
killall karabiner_session_monitor
killall karabiner_console_user_server

# Update version file

cp \
    '/Library/Application Support/org.pqrs/Karabiner-Elements/package-version' \
    '/Library/Application Support/org.pqrs/Karabiner-Elements/version'

# If plistFilePath is already bootstrapped and disabled, launchctl bootstrap will fail until it is enabled again.
# So we should enable it first, and then bootstrap and enable it.
launchctl enable system/org.pqrs.karabiner.karabiner_kextd
launchctl bootstrap system /Library/LaunchDaemons/org.pqrs.karabiner.karabiner_kextd.plist
launchctl enable system/org.pqrs.karabiner.karabiner_kextd

launchctl enable system/org.pqrs.karabiner.karabiner_grabber
launchctl bootstrap system /Library/LaunchDaemons/org.pqrs.karabiner.karabiner_grabber.plist
launchctl enable system/org.pqrs.karabiner.karabiner_grabber

launchctl enable system/org.pqrs.karabiner.karabiner_observer
launchctl bootstrap system /Library/LaunchDaemons/org.pqrs.karabiner.karabiner_observer.plist
launchctl enable system/org.pqrs.karabiner.karabiner_observer

exit 0
